<?php

require_once(APP.'libs'.DS.'system_properties.php');
require_once(APP.'libs'.DS.'my_app_model.php');

App::import('Vendor','/infolex/app_config');
class Luck extends MyAppModel
{
	var $name='Luck';
	var $validate = array();
	
	/**
	 * 类型
	 * array(
        'uid'=>'',
        'pid'=>'',
        'time'=>'',
        'type'=>'',
        'is_get'=>'',
        'how_get'=>'',
        'limit_time'=>'',
        'coupon'=>'',
        'count'=>'',
        );
	 *
	 * @param unknown_type $arr
	 * @return unknown
	 */
	function saveLuck($arr) {
	    $sql = 'insert into g_lucks set ';
	    $list = array();
	    foreach ($arr as $k=>$v) {
	        $v = mysql_escape_string($v);
	        $list[] = "`$k`='$v'";
	    }
	    $sql .= join(',', $list);
	    return $this->query($sql);
	}

	/* cy add, 2011-4-6 */
	function getLuckIdByContent($user_id, $product_id){
		$sql = sprintf("select max(seqid) as id from g_lucks where uid=%d and pid=%d", intval($user_id), intval($product_id));
		$ret = $this->query($sql);
		if (empty($ret) || empty($ret[0][0]['id'])){
			return 0;
		}
		return $ret[0][0]['id'];
	}

	function getMyKuaidi($uid) {
	    $sql = "select * from g_lucks where uid=$uid and admin_is_sent='y' and 	admin_express_sn IS NOT NULL order by seqid desc";
	    //echo $sql 
	    $data = $this->query($sql);
	    $ret = $this->_fillProductInfo($data);
	    return $ret;
	}
	/**
	 * 更新字段
	 *
	 * @param unknown_type $id
	 * @param unknown_type $arr
	 * @return unknown
	 */
	function updateLuck($uid, $id, $arr) {
	    $uid = intval($uid);
	    if (is_array($id)) {
	        foreach ($id as $k=>$v) {
	            $id[$k] = intval($v);
	        }
	        $id = array_merge(array_unique($id));
	    } else {
	        $id = array(intval($id));
	    }
	    $list = array();
	    foreach ($arr as $k=>$v) {
	        $v = mysql_escape_string($v);
	        $list[] = "`$k`='$v'";
	    }
	    foreach ($id as $i) {
    	    $sql = 'update g_lucks set';
    	    $sql .= join(',', $list);
    	    $sql .=" where uid=$uid and seqid=$i";	  
    	    $this->query($sql);  
    	    
	    }
	    return true;
	}
	
	/**
	 * 保存分享
	 *
	 * @param unknown_type $id
	 * @param unknown_type $detail
	 * @return unknown
	 */
	function saveShare($uid, $id, $detail) {
	    return $this->updateLuck($uid, $id, array('is_share'=>'y','share_time'=>date('Y-m-d H:i:s'),'share_detail'=>json_encode($detail)));
	}
	
	function getShare($pids, $start, $count, &$total) {
	    if (!empty($pids)) {
			$huan_pids = array();
			$zhuan_pids = array();
    	    foreach ($pids as $k=>$v) {
    	        $tpid = intval($v);
				if (0 === $tpid){
					continue;
				} else if ($tpid > 0){
					$zhuan_pids[] = $tpid;
				} else {
					$huan_pids[] = -$tpid;
				}
    	    }
			if ($huan_pids && !$zhuan_pids){
				$pids_str = sprintf(" and (pid in (%s) and how_get='huan') ", implode(',', $huan_pids));
			}  else if ($zhuan_pids && !$huan_pids){
				$pids_str = sprintf(" and (pid in (%s) and how_get='zhuan') ", implode(',', $zhuan_pids));
			} else if ($huan_pids && $zhuan_pids){
				$pids_str = sprintf(" and ((pid in (%s) and how_get='zhuan') or(pid in (%s) and how_get='huan'))", implode(',', $zhuan_pids), implode(',', $huan_pids));
			}
	    } else {
	        $pids_str = '';
	    }
	    $data = $this->query("select SQL_CALC_FOUND_ROWS g_lucks.*,g_users.g_name,g_users.g_head from g_lucks inner join g_users on g_lucks.uid = g_users.g_id where is_share='pass' $pids_str order by share_time desc limit $start, $count");
	    $t = $this->query("SELECT FOUND_ROWS() as n");//getNumRows();
	    $total = $t[0][0]['n'];

	    return $this->_fillProductInfo($data);   
	}
	/**
	 * fill product info for list
	 */
	function _fillProductInfo($data) {
	    if (empty($data)) {
	        return array();
	    }
	    $zhuan_ids = array();
	    $huan_ids = array();
	    foreach ($data as $da) {
	        $d = $da['g_lucks'];
	        if ($d['how_get'] == 'zhuan') {
	            $zhuan_ids[] = $d['pid'];
	        } else if ($d['how_get'] == 'huan') {
	            $huan_ids[] = $d['pid'];
	        }	        
	    }
        $zhuan_info = $this->getPInfo($zhuan_ids, 'g_products');
        $huan_info = $this->getPInfo($huan_ids, 'g_changes');
	    foreach ($data as $k=>$da) {
	        $d = $da['g_lucks'];
	        if ($d['how_get'] == 'zhuan') {
	            $data[$k]['g_lucks']['product_info'] = $zhuan_info[$d['pid']];
	        } else if ($d['how_get'] == 'huan') {
	            $data[$k]['g_lucks']['product_info'] = $huan_info[$d['pid']];
	        }	   
	        $data[$k]['g_lucks']['share_detail'] = json_decode($d['share_detail'],1);
	           
	    }	    
	    return $data;
	}
	function getShareById($id) {
	    $id = intval($id);
	    $sql = 'select * from g_lucks where seqid='.$id;
	    $data = $this->query($sql);
	    if (empty($data[0]['g_lucks'])  ) {
	        return array();
	    } else {
	        return $data[0]['g_lucks'];
	    }
	}
	/**
	 * 获取所有luck然后进行处理
	 *
	 * @param unknown_type $uid
	 * @return unknown
	 */
	function getMyAllLuck($uid) {
		if (CY_DAOGUI_CAPTCHA_OPEN){
		$uid = intval($uid);
		$sql = 'select * from g_lucks where uid='.$uid .' order by seqid desc';
		$data = $this->query($sql);  

		//未发快递 type='kuaidi' is_get='-'状态
		$kuaidi_not_send = array();
		//柜台未处理是否领取 type='guitai' is_get='-'状态 
		$guitai_not_send = array();
		//商家未处理是否领取 type='shangjiafahuo' is_get='-'状态
		$shangjia_not_send = array();
		//优惠券 默认已经领取 type='coupon'
		$coupon_get = array();
		//以上各种除了优惠券 其他的is_get领取处于'y'状态的
		$luck_get = array();
		//柜台未领取的 为 type='guitai' is_get='n' 不在前台显示。
		$zhuan_ids = array();
		$huan_ids = array();
		foreach ($data as $da) {
			$d = $da['g_lucks'];
			if ($d['how_get'] == 'zhuan') {
				$zhuan_ids[] = $d['pid'];
			} else if ($d['how_get'] == 'huan') {
				$huan_ids[] = $d['pid'];
			}
		}
		$zhuan_info = $this->getPInfo($zhuan_ids, 'g_products');
		$huan_info = $this->getPInfo($huan_ids, 'g_changes');

		foreach ($data as $k=>$da) {
			$d = $da['g_lucks'];
			if ($d['how_get'] == 'zhuan') {
				$data[$k]['g_lucks']['product_info'] = $zhuan_info[$d['pid']];
			} else if ($d['how_get'] == 'huan') {
				$data[$k]['g_lucks']['product_info'] = $huan_info[$d['pid']];
			}	        
		}	 
		$guitai_not_send_seqids = array(); // cy add
		foreach ($data as $da) {  
			$d = $da['g_lucks'];
			if ($d['type'] == 'kuaidi' && $d['is_get'] == '-')  {
				$kuaidi_not_send[] = $d;
			} else if ($d['type'] == 'guitai' && ($d['is_get'] == '-' || $d['is_get'] == 'n')) {
				$guitai_not_send[] = $d;
				$guitai_not_send_seqids[] = $d['seqid'];
			} else if ($d['type'] == 'shangjiafahuo'&& ($d['is_get'] == '-' || $d['is_get'] == 'n')) {
				$shangjia_not_send[] = $d;
			} else if ($d['type'] == 'coupon') {
				$coupon_get[] = $d;
			} else if ($d['is_get'] == 'y') {
				$luck_get[] = $d;
			} 	        
		}

		if (!empty($guitai_not_send_seqids)){
			$guitai_not_send_captchas = $this->getLuckCaptchasByIds($guitai_not_send_seqids);
			if (!empty($guitai_not_send_captchas)){
				$g_hash = array();
				foreach($guitai_not_send_captchas as $g){
					$g = $g['g_luckcaptcha'];
					$g_hash[$g['luck_id']] = $g;
				}

				foreach($guitai_not_send as &$g){
					$g['captcha'] = $g_hash[$g['seqid']];
				}
			}
		}

		$ret = array(
				'kuaidi_not_send' => $kuaidi_not_send,
				'guitai_not_send' => $guitai_not_send,
				'shangjia_not_send' => $shangjia_not_send,
				'coupon_get' => $coupon_get,
				'luck_get' => $luck_get,
				);
		return $ret;	    
		} else {
		$uid = intval($uid);
		$sql = 'select * from g_lucks where uid='.$uid .' order by seqid desc';
		$data = $this->query($sql);  
		
		//未发快递 type='kuaidi' is_get='-'状态
		$kuaidi_not_send = array();
		//柜台未处理是否领取 type='guitai' is_get='-'状态 
		$guitai_not_send = array();
		//商家未处理是否领取 type='shangjiafahuo' is_get='-'状态
		$shangjia_not_send = array();
		//优惠券 默认已经领取 type='coupon'
		$coupon_get = array();
		//以上各种除了优惠券 其他的is_get领取处于'y'状态的
		$luck_get = array();
		//柜台未领取的 为 type='guitai' is_get='n' 不在前台显示。
		$zhuan_ids = array();
		$huan_ids = array();
		foreach ($data as $da) {
			$d = $da['g_lucks'];
			if ($d['how_get'] == 'zhuan') {
				$zhuan_ids[] = $d['pid'];
			} else if ($d['how_get'] == 'huan') {
				$huan_ids[] = $d['pid'];
			}
		}
		$zhuan_info = $this->getPInfo($zhuan_ids, 'g_products');
		$huan_info = $this->getPInfo($huan_ids, 'g_changes');
		
		foreach ($data as $k=>$da) {
			$d = $da['g_lucks'];
			if ($d['how_get'] == 'zhuan') {
				$data[$k]['g_lucks']['product_info'] = $zhuan_info[$d['pid']];
			} else if ($d['how_get'] == 'huan') {
				$data[$k]['g_lucks']['product_info'] = $huan_info[$d['pid']];
			}	        
		}	 
		foreach ($data as $da) {  
			$d = $da['g_lucks'];
			if ($d['type'] == 'kuaidi' && $d['is_get'] == '-')  {
				$kuaidi_not_send[] = $d;
			} else if ($d['type'] == 'guitai' && ($d['is_get'] == '-' || $d['is_get'] == 'n')) {
				$guitai_not_send[] = $d;
			} else if ($d['type'] == 'shangjiafahuo'&& ($d['is_get'] == '-' || $d['is_get'] == 'n')) {
				$shangjia_not_send[] = $d;
			} else if ($d['type'] == 'coupon') {
				$coupon_get[] = $d;
			} else if ($d['is_get'] == 'y') {
				$luck_get[] = $d;
			} 	        
		}

		$ret = array(
		   'kuaidi_not_send' => $kuaidi_not_send,
		   'guitai_not_send' => $guitai_not_send,
		   'shangjia_not_send' => $shangjia_not_send,
		   'coupon_get' => $coupon_get,
		   'luck_get' => $luck_get,
		);
		return $ret;	    
		}
	}

	/* cy add, 2011-4-6 */
	function getLuckCaptchasByIds($luck_ids){
		$sql = sprintf("select * from g_luckcaptcha where luck_id in (%s)",
			implode(',', $luck_ids)
			);
		$ret = $this->query($sql);

		return $ret;
	}

	function getPInfo($ids, $table) {
	    
	    if (empty($ids)) {
	        return array();
	    }
	    foreach ($ids as $k=>$v) {
	        $ids[$k] = intval($v);
	    }
	    $ids = array_merge(array_unique($ids));
	    $sql = "select g_name,g_id,g_img,g_extra_url,g_protal_url from `{$table}` where g_id in (".join(',',$ids).')';
	    $data = $this->query($sql);
	    $ret = array();
	    if (empty($data)) {
	        return $data;
	    } else {
	       foreach ($data as $da) {
	           $ret[$da[$table]['g_id']] = $da[$table];
	       }
	    }
	    return $ret;
	}
	/**
	 * 获取首页的幸运用户
	 *
	 * @param unknown_type $start
	 * @param unknown_type $count
	 * @param unknown_type $total
	 * @return unknown
	 */
	function listAllLuckUsers($start, $count, &$total) {
	    $start = intval($start);
	    $count = intval($count);
		
		$sql = sprintf("select g_users.g_name as username,g_users.g_head,g_lucks.* from (select * from g_lucks order by seqid desc limit %d, %d) as g_lucks inner join g_users on(g_lucks.uid=g_users.g_id)", intval($start), intval($count));
		$data = $this->query($sql);
		$total = 500; // don't allow to see more
	    return $this->_fillProductInfo($data);

	    $data = $this->query("SELECT SQL_CALC_FOUND_ROWS g_users.g_name as username,g_users.g_head,g_lucks.* FROM `g_lucks` inner join g_users on `g_lucks`.uid = g_users.g_id WHERE 1 order by time desc limit $start, $count");
	    $t = $this->query("SELECT FOUND_ROWS() as n");//getNumRows();
	    $total = $t[0][0]['n'];
	    return $this->_fillProductInfo($data);
	    
	}	
	/**
	 * 获取一个luck的所有用户
	 *
	 * @param unknown_type $pid
	 * @return unknown
	 */
	function getLuckUserByProduct($pid, &$total, $how = 'zhuan') {
	    if ($how!='zhuan'){
	        $how = 'huan';
	    }
	    $pid = intval($pid);
	    $sql = "select SQL_CALC_FOUND_ROWS g_name,uid,time from g_lucks inner join g_users on g_users.g_id=g_lucks.uid where pid='$pid' and how_get='$how' and seqid>0 order by seqid desc limit 100";
	    $data = $this->query($sql);  
	    $t = $this->query("SELECT FOUND_ROWS() as n");//getNumRows();
	    $total = $t[0][0]['n'];
	    if (empty($data)){
	        return array();
	    } else {
	       return $data;
	    }
	}
	
	/**
	 * 检查是否已经中奖过
	 *
	 * @param unknown_type $user_id
	 * @param unknown_type $id
	 * @return unknown
	 */
	function checkApplyOK($uid, $pid) {
	    $uid = intval($uid);
	    $pid = intval($pid);
	    
	    $sql = "select seqid from g_lucks where uid={$uid} and pid={$pid} and how_get='zhuan' limit 1";
	    $data = $this->query($sql);  
	    if (empty($data)) {
	        return 0;
	    } else {
	        return 1;
	    }
	}	
	/**
	 * 检查本月是否已经兑换过
	 *
	 * @param unknown_type $user_id
	 * @param unknown_type $id
	 * @return unknown
	 */
	function checkExchangeOK($uid, $pid) {
	    $uid = intval($uid);
	    $pid = intval($pid);
	    $dayof1 = date('Y-m-1');
	    $sql = "select seqid from g_lucks where uid={$uid} and pid={$pid} and type='huan' and time>='$dayof1' limit 1";
	    $data = $this->query($sql);  
	    if (empty($data)) {
	        return 0;
	    } else {
	        return 1;
	    }
	}	

	/**
	 * 获取未分想的数量
	 *
	 * @param unknown_type $uid
	 * @return unknown
	 */
	function getUnShareCount($uid) {
	    $uid = intval($uid);
	    $sql = "select count(1) as n from g_lucks where uid=$uid and is_share='n' and type<>'coupon' and is_get='y' ";
	    $data = $this->query($sql);  
	    return $data[0][0]['n'];
	}
	/**
	 * 获取未分想的数量
	 *
	 * @param unknown_type $uid
	 * @return unknown
	 */
	function getLuckCount($uid) {
	    $uid = intval($uid);
	    $sql = "select count(1) as n from g_lucks where uid=$uid ";
	    $data = $this->query($sql);  
	    return $data[0][0]['n'];
	}	
	
	function getShareGroup() {
	    $sql = "select * from g_sharegroups where 1 order by `order`";
	    $data = $this->query($sql);  
	    return $data;
	}
}
